"use client"

import { useParams } from "next/navigation"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import { Loader2, Play, Upload } from "lucide-react"
import { useRef, useState } from "react"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { algorithms } from "../lib/algorithms"
import { GraphVisualization } from "../lib/components/graph-visualization"
import { Textarea } from "@/components/ui/textarea"

// 添加类型定义
type ConfigOption = {
  id: string;
  label: string;
  type: string;
  defaultValue?: any;
  placeholder?: string;
  options?: string[];
  required?: boolean;
  optionLabels?: Record<string, string>;
  accept?: string;
};

export default function AlgorithmPage() {
  const params = useParams()
  const algorithmId = params.id as keyof typeof algorithms
  const algorithm = algorithms[algorithmId]

  const [config, setConfig] = useState<Record<string, any>>(() => {
    // 初始化配置
    const initialConfig: Record<string, any> = {}
    if (algorithm) {
      algorithm.configOptions.forEach((option) => {
        if (option.defaultValue !== undefined) {
          initialConfig[option.id] = option.defaultValue
        }
      })
    }
    return initialConfig
  })

  const [result, setResult] = useState<any>(null)
  const [isExecuting, setIsExecuting] = useState(false)
  const [activeTab, setActiveTab] = useState("config")
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [dragActive, setDragActive] = useState(false)
  const [uploadError, setUploadError] = useState<string>("")

  if (!algorithm) {
    return (
      <Alert variant="destructive">
        <AlertTitle>算法不存在</AlertTitle>
        <AlertDescription>找不到ID为 "{algorithmId}" 的算法。请返回首页选择有效的算法。</AlertDescription>
      </Alert>
    )
  }

  const handleConfigChange = (id: string, value: any) => {
    setConfig((prev) => ({
      ...prev,
      [id]: value,
    }))
  }

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true)
    } else if (e.type === "dragleave") {
      setDragActive(false)
    }
  }

  const handleDrop = (e: React.DragEvent, id: string) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    const files = e.dataTransfer.files
    handleFileChange(id, files)
  }

  const handleFileChange = (id: string, files: FileList | null) => {
    setUploadError("")
    if (files && files.length > 0) {
      const file = files[0]
      const option = algorithm.configOptions.find(opt => opt.id === id)
      if (!option) return

      // 验证文件类型
      if (option.accept) {
        const acceptedTypes = option.accept.split(',').map(type => type.trim())
        const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
        if (!acceptedTypes.includes(fileExtension)) {
          setUploadError(`请上传${option.accept}格式的文件`)
          return
        }
      }

      // 验证文件大小（例如限制为10MB）
      if (file.size > 100 * 1024 * 1024) {
        setUploadError("文件大小不能超过10MB")
        return
      }

      setConfig((prev) => ({
        ...prev,
        [id]: file,
      }))
    }
  }

  const executeAlgorithm = async () => {
    setIsExecuting(true)
    setActiveTab("result")

    try {
      const result = await algorithm.execute(config)
      setResult(result)
    } catch (error) {
      console.error("算法执行错误:", error)
      setResult({
        error: "算法执行过程中发生错误",
        details: error instanceof Error ? error.message : String(error),
      })
    } finally {
      setIsExecuting(false)
    }
  }

  return (
    <div>
      <div className="flex flex-col gap-4">
        <div>
          <h1 className="text-3xl font-bold">{algorithm.name}</h1>
          <p className="text-muted-foreground mt-2">{algorithm.description}</p>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="config">配置</TabsTrigger>
            <TabsTrigger value="result">结果</TabsTrigger>
          </TabsList>

          <TabsContent value="config">
            <Card>
              <CardHeader>
                <CardTitle>算法配置</CardTitle>
                <CardDescription>设置算法参数并执行</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {(algorithm?.configOptions || []).map((option: ConfigOption) => (
                  <div key={option.id} className="space-y-2">
                    <Label htmlFor={option.id}>{option.label}</Label>

                    {option.type === "select" ? (
                      <Select
                        value={String(config[option.id] || "")}
                        onValueChange={(value) => handleConfigChange(option.id, value)}
                      >
                        <SelectTrigger id={option.id}>
                          <SelectValue placeholder="选择选项" />
                        </SelectTrigger>
                        <SelectContent>
                          {option.options?.map((opt) => (
                            <SelectItem key={opt} value={opt}>
                              {option.optionLabels?.[opt] || opt}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    ) : option.type === "number" ? (
                      <Input
                        id={option.id}
                        type="number"
                        value={config[option.id] || ""}
                        onChange={(e) => handleConfigChange(option.id, Number(e.target.value))}
                      />
                    ) : option.type === "file" ? (
                      <div
                        className={`flex flex-col items-center justify-center border-2 ${
                          dragActive ? "border-primary" : "border-dashed"
                        } rounded-md p-6 cursor-pointer hover:bg-muted/50 transition-colors relative`}
                        onClick={() => fileInputRef.current?.click()}
                        onDragEnter={(e) => handleDrag(e)}
                        onDragLeave={(e) => handleDrag(e)}
                        onDragOver={(e) => handleDrag(e)}
                        onDrop={(e) => handleDrop(e, option.id)}
                      >
                        <input
                          ref={fileInputRef}
                          type="file"
                          id={option.id}
                          accept={option.accept}
                          className="hidden"
                          onChange={(e) => handleFileChange(option.id, e.target.files)}
                        />
                        <Upload className={`h-10 w-10 ${dragActive ? "text-primary" : "text-muted-foreground"} mb-2`} />
                        <p className="text-sm text-muted-foreground">
                          {config[option.id] ? config[option.id].name : "点击或拖拽文件到此处上传"}
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">支持 {option.accept} 格式</p>
                        {uploadError && (
                          <div className="absolute bottom-2 left-2 right-2 bg-destructive/10 text-destructive text-sm p-2 rounded">
                            {uploadError}
                          </div>
                        )}
                      </div>
                    ) : option.type === "textarea" ? (
                      <Textarea
                        id={option.id}
                        value={config[option.id] || ""}
                        onChange={(e) => handleConfigChange(option.id, e.target.value)}
                        placeholder={option.placeholder}
                        className="min-h-[200px]"
                      />
                    ) : (
                      <Input
                        id={option.id}
                        value={config[option.id] || ""}
                        onChange={(e) => handleConfigChange(option.id, e.target.value)}
                      />
                    )}
                  </div>
                ))}
              </CardContent>
              <CardFooter>
                <Button onClick={executeAlgorithm} disabled={isExecuting} className="w-full">
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      执行算法
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>

          <TabsContent value="result">
            <Card>
              <CardHeader>
                <CardTitle>执行结果</CardTitle>
                <CardDescription>
                  {isExecuting
                    ? "算法正在执行中..."
                    : result
                      ? `执行完成，耗时: ${result.executionTime}`
                      : "尚未执行算法"}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {isExecuting ? (
                  <div className="flex flex-col items-center justify-center py-8">
                    <Loader2 className="h-8 w-8 animate-spin text-primary mb-4" />
                    <p>正在执行算法，请稍候...</p>
                  </div>
                ) : result ? (
                  <div className="space-y-4">
                    {result.error ? (
                      <Alert variant="destructive">
                        <AlertTitle>{result.error}</AlertTitle>
                        <AlertDescription>{result.details}</AlertDescription>
                      </Alert>
                    ) : (
                      <>
                        {algorithmId === "dynamic-graph-generation" ? (
                          <>
                            <div>
                              <h3 className="text-lg font-medium mb-2">数据摘要</h3>
                              <div className="p-4 bg-muted rounded-md">
                                <pre className="whitespace-pre-wrap">{result.result.summary}</pre>
                              </div>
                            </div>

                            <Separator />

                            <div>
                              <h3 className="text-lg font-medium mb-2">执行步骤</h3>
                              <div className="space-y-2">
                                {result.steps.map((step: string, index: number) => (
                                  <div key={index} className="p-2 border rounded-md">
                                    <p>{step}</p>
                                  </div>
                                ))}
                              </div>
                            </div>

                            <Separator />

                            <div>
                              <h3 className="text-lg font-medium mb-2">图谱可视化</h3>
                              <GraphVisualization data={result.result.graphData} />
                            </div>
                          </>
                        ) : (
                          <>
                            <div>
                              <h3 className="text-lg font-medium mb-2">结果</h3>
                              <div className="p-4 bg-muted rounded-md">
                                <pre className="whitespace-pre-wrap">{result.result}</pre>
                              </div>
                            </div>

                            <Separator />

                            <div>
                              <h3 className="text-lg font-medium mb-2">执行步骤</h3>
                              <div className="space-y-2">
                                {result.steps.map((step: string, index: number) => (
                                  <div key={index} className="p-2 border rounded-md">
                                    <p>{step}</p>
                                  </div>
                                ))}
                              </div>
                            </div>
                          </>
                        )}
                      </>
                    )}
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                    <p>请先配置并执行算法</p>
                  </div>
                )}
              </CardContent>
              <CardFooter>
                <Button onClick={executeAlgorithm} disabled={isExecuting} className="w-full">
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      重新执行
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}

